package com.ruoyi.baseData.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.baseData.domain.SerialNumber;
import com.ruoyi.baseData.domain.Team;
import com.ruoyi.baseData.service.SerialNumberService;
import com.ruoyi.baseData.mapper.SerialNumberMapper;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 */
@Service
public class SerialNumberServiceImpl implements SerialNumberService{

    @Resource
    SerialNumberMapper serialNumberMapper;

    @Override
    public String getNextSnByCode(String code) {
        Integer maxNumber = 0;
        String preValue = "";
        String userName = SecurityUtils.getUsername();
        MPJLambdaWrapper<SerialNumber> wrapper = new MPJLambdaWrapper<SerialNumber>()
                .eq(SerialNumber::getCode, code)
                .ne(Team::getDelFlag, 1);
        SerialNumber serialNumber = serialNumberMapper.selectOne(wrapper);

        if(ObjectUtil.isEmpty(serialNumber)) {
            return null;
        }
        /**
         * 获取最大值
         */
        maxNumber = serialNumber.getMaxNumber();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String formattedDate = dateFormat.format(new Date());

        //如果相等
        if(formattedDate.equals(serialNumber.getPreRuleValue())) {
            maxNumber = serialNumber.getMaxNumber() + 1;
        } else {
            maxNumber = 1;
        }

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(String.format("%0"+serialNumber.getCodeCnt()+"d",Integer.valueOf(maxNumber)));
        serialNumber.setMaxNumber(maxNumber);
        serialNumber.setPreRuleValue(formattedDate);
        serialNumberMapper.updateById(serialNumber);
//
//        if(checkDateChange(serialNumberItem.getRule(), serialNumber.getPreRuleValue())) {
//            maxNumber = 1;
//        } else {
//
//        }
        return  formattedDate + stringBuilder.toString();

    }
}




